var location = require("../../../../mybehaviors/location/location");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [location],
  data: {
    active: 2,
    publisherList: [],
    myLocation: {
      address: "",
      city: "",
      point: ''
    },
    classifyData: [],
    publishLists: {
      recommendCategory: [],
      nearby_shifu: [],
      carousel_images: []
    },
    type: "",
    Height: "",
    //新加的参数
    msgShow:false,
    TemplateArray:[],
    tempArray:{},
    is_shifu: 0,//师傅：1是0否
    is_shop:0,//是否平台管理员
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      type: options && options.type ? options.type : '',
      active:  options && options.type ? options.type * 1 : 2
    })
    this.getmanage();
    this.getTemplate();
  },
  getmanage() {
    app._getNetWork({
      url: app.getNetAddresss('plugin.be-within-call.frontend.manage.my'),
      success: resdata => {
        let { result, data, msg } = resdata.data;
        if (result) {
          this.setData({
            is_shifu: data.is_shifu,
            is_shop:data.is_shop
          })
        } else {
          app.tips(msg);
        }
      }
    })
  },
  tempSetting() { //查询订阅消息
    
    wx.getSetting({
      withSubscriptions: true,
      success:(res) => {
        this.getSettingData(res);
      },
      fail:(err) => {
        // resolve(false);
        console.log('getSetting',err);
      },
    });
    
  },
  getSettingData(res) {
    let mainSwitch = res.subscriptionsSetting?.mainSwitch;
    //检查订阅消息的设置是否关闭
    if(!mainSwitch) {
      this.modeSetting();
    }
    let itemSettings = res.subscriptionsSetting?.itemSettings;
    if ((!itemSettings && this.data.is_shifu) || (!itemSettings && this.data.is_shop) ) {
      if((!app.globalData.informShow)) {
        this.setData({
          msgShow: true
        });
        return;
      }
    }
    // 获取消息模板对象
    let demandObj = this.data.tempArray['new_demand_order_master'];
    let orderObj  = this.data.tempArray['reservation_order_master'];
    let acceptObj = this.data.tempArray['accept_order_master'];
    let identityObj = this.data.tempArray['publisher_identity_examine_shop'];
    let publisherObj = this.data.tempArray['publisher_demand_examine_shop'];
    // 获取已订阅的消息模板ID
    const subscribedTemplateIds = Object.keys(itemSettings);
      // 检查身份相关的消息模板
      if(this.data.is_shifu) {
        console.log(orderObj);
        console.log(demandObj);
        console.log(acceptObj,'acceptObjacceptObj');
        //后期优化可以考虑固定一个数组参数遍历判断状态是否开启
        //授权后，等待通知的，不走查询设置和后端消息通知
        if(orderObj.is_open) {
          this.checkSubscription(subscribedTemplateIds,orderObj, this.data.is_shifu);
        }
        if(demandObj.is_open) {
          this.checkSubscription(subscribedTemplateIds,demandObj, this.data.is_shifu);
        }
        if(acceptObj.is_open) {
          this.checkSubscription(subscribedTemplateIds,acceptObj, this.data.is_shifu);
        }
        
      }
      if(this.data.is_shop) {
        if(identityObj.is_open) {
          this.checkSubscription(subscribedTemplateIds,identityObj, this.data.is_shop);
        }
        if(publisherObj.is_open) {
          this.checkSubscription(subscribedTemplateIds,publisherObj, this.data.is_shop);
        }
        
      }
  },
   // 检查每个消息模板的订阅状态
   checkSubscription(tempArray,templateObj, condition) {
    console.log(templateObj);
    console.log(!tempArray.includes(templateObj.template_id),'template_id');
    console.log(templateObj.is_open);
    console.log(condition);
    if (
      !tempArray.includes(templateObj.template_id) &&
      templateObj.is_open &&
      condition
    ) {
      //判断是否退出小程序，重置弹窗
      if(!app.globalData.informShow) {
        this.setData({
          msgShow: true
        });
      }
    } else {
      //查询订阅消息授权状态，未授权，累加发送订阅消息
      if(!templateObj.authorize && tempArray.includes(templateObj.template_id)) {
        this.setData({
          msgShow: true
        });
      } 
    }
  },
  modeSetting() {
    Dialog.confirm({
      message: '是否打开设置页',
    })
    .then(() => {
      // on confirm
      wx.openSetting({
        withSubscriptions:true,
        success (res) {
          let mainSwitch = res.subscriptionsSetting?.mainSwitch;
          if(mainSwitch) {
            wx.showToast({
              icon: "none",
              title: "获取订阅消息权限成功",
              duration: 1500,
            });
          } else {
            wx.showToast({
              icon: "none",
              title: "获取订阅消息权限失败",
              duration: 1500,
            });
          }
        }
      })
      
    })
    .catch(() => {
      // on cancel
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
   this.ready();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */ 
  onReachBottom() {

  },
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this._getLocation((mapdata,e)=>{
      this.setData({
        'myLocation.address': mapdata.address,
        'myLocation.city': mapdata.address_component.city ? mapdata.address_component.city : mapdata.address_component.province,
        'myLocation.point': e
      });
      this.getClassifyData();
    });
  },
  splitArr (arr,num) {
    var res=[];
    for (var i = 0,len = arr.length; i < len; i+=num) {
      res.push(arr.slice(i, i+num));
    }
    return res
  },
  goMoreList(item) {
   wx.navigateTo({
     url:  `/packageJ/anytime_service/home/publisher_list/index?type=${item.currentTarget.dataset.type}&myLocation=${JSON.stringify(this.data.myLocation)}&id=${item.currentTarget.dataset.id}`,
   });
  },
  // 附近技师更多
  tosearch() {
    wx.navigateTo({
      url:  `/packageJ/anytime_service/home/search/index?name=技师`,
    });
  },
  goividualNeeds(item) {
    wx.navigateTo({
      url:  `/packageJ/anytime_service/home/individual_needs/index?type=${item.currentTarget.dataset.type}&order_id=${item.currentTarget.dataset.id}`,
    });
  },
  // 跳转技师师傅主页
  goTechnicianHome(item) {
    wx.navigateTo({
      url:  `/packageJ/anytime_service/home/technician_home/index?id=${item.currentTarget.dataset.id}`,
    });
  },
  // 获取分类
  getClassifyData() {
    app._postNetWork({
      url: app.getNetAddresss("plugin.be-within-call.frontend.index.get-category-list"),
      data: {
        sort_type: this.data.active
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result != 1) {
          app.tips(res.data.msg);
          return;
        } 
        this.setData({
          classifyData: this.splitArr(res.data,10),
        });
        this.getData();
      },
    });
  },
  //抢单大厅
  //平台：（指定1个或多个人接收通知）

  //师傅:新需求订单通知
  //接单成功通知（师傅）
  //预约单通知（师傅）
  //获取模板ID
  getTemplate(type) {
    let urlStr = app.getNetAddresss("plugin.be-within-call.frontend.notice-template");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let array = [];
          let data = res.data;
          for(let key in data) {
            if((data[key].key  == 'new_demand_order_master' || data[key].key  == 'accept_order_master' || data[key].key  == 'reservation_order_master') && this.data.is_shifu) {
              if(data[key].is_open) {
                array.push(data[key].template_id);
              }
            }
            if((data[key].key  == 'publisher_identity_examine_shop' || data[key].key  == 'publisher_demand_examine_shop')
              && this.data.is_shop) {
              if(data[key].is_open) {
                array.push(data[key].template_id);
              }
            }
          }
          this.setData({
            TemplateArray: array,
            tempArray:data,
          });
          if(type) {
            wx.requestSubscribeMessage({
              tmplIds: this.data.TemplateArray,
              success: (res) => {
                let tempArray = [];
                for(let key in data) {
                  if(res[data[key].template_id] == 'accept') {
                    tempArray.push(data[key].key)
                  }
                }
                this.setData({
                  msgShow:false
                })
                this.setTempLog(tempArray);
                // app.globalData.informShow = true;
              },
              fail: (err) => {
                console.log(err);
                this.setData({
                  msgShow:false
                })
                // app.globalData.informShow = true;
              },
            });
          } else {
            this.tempSetting();
          }
          
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  setTempLog(tempArray) {
    let urlStr = app.getNetAddresss("plugin.be-within-call.frontend.notice-template.save-log");
    app._postNetWork({
      url: urlStr,
      data:{template_keys:tempArray},
      success: resdata => {
        let { result, data, msg } = resdata.data;
        if (result) {
          app.tips(msg);
        } else {
          app.tips(msg);
        }
      }
    })
  },
  msgtempClick() {
    this.getTemplate(true);
  },
  closeMsg() {
    this.setData({
      msgShow:false,
    });
    app.globalData.informShow = true;
  },
  splitArr (arr,num) {
    var res=[];
    for (var i = 0,len = arr.length; i < len; i+=num) {
      res.push(arr.slice(i, i+num));
    }
    return res
  },
  getData() {
    let form = {sort_type: this.data.active };
    let url = "plugin.be-within-call.frontend.index.tab-one";
    if(this.data.active == 2) {
      form = {
        lng: this.data.myLocation ? this.data.myLocation.point.lng : "",
        lat: this.data.myLocation ? this.data.myLocation.point.lat : "",
        sort_type: this.data.active
      }
      url = "plugin.be-within-call.frontend.index.tab-two"
    }else if(this.data.active == 3) {
      url = 'plugin.be-within-call.frontend.index.tab-three'
    }
    app._postNetWork({
      url: app.getNetAddresss(url),
      data: form,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result != 1) {
          app.tips(res.data.msg);
          return;
        } 
        this.setData({
          ['publishLists.recommendCategory']: res.data.recommendCategory,
          ['publishLists.nearby_shifu']:  this.data.active == 2 ? res.data.nearby_shifu : [],
          ['publishLists.carousel_images']:  res.data.carousel_images
        });
      },
    });
  },
  changeTab(val) {
    console.log(val);
    this.setData({
      active: val.detail.name
    })
    this.getClassifyData();
  },
  imgHeight: function(e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = winWid * imgh / imgw + "px"; //等比设置swiper的高度。 即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
      Height: swiperH //设置高度
    });
  },
})